#include <stdio.h>

#define N 7

// 合并左子数组和右子数组
void merge(int *A, int left, int mid, int right)
{
    static int tmp[N];
    // 初始化左子数组和右子数组的起始索引
    int i = left, j = mid + 1, k = 0;
    while (i <= mid && j <= right)
    {
        if (A[i] < A[j])
        {
            tmp[k++] = A[i++];
        }
        else
        {
            tmp[k++] = A[j++];
        }
    }
    while (i <= mid)
    {
        tmp[k++] = A[i++];
    }
    while (j <= right)
    {
        tmp[k++] = A[j++];
    }
    // 将临时数组 tmp 中的元素复制回原数组 A 的对应区间
    for (int t = 0; t < k; ++t)
    {
        A[t + left] = tmp[t];
    }
}

void merge_sort(int *A, int left, int right)
{
    if (left >= right)
    {
        return;
    }
    int mid = left + (right - left) / 2;
    // left
    merge_sort(A, left, mid);
    // right
    merge_sort(A, mid + 1, right);
    // merge
    merge(A, left, mid, right);
}
int main()
{
    int A[N] = {
        49,
        38,
        65,
        97,
        76,
        13,
        27,
    };
    merge_sort(A, 0, N - 1);
    for (int i = 0; i < N; i++)
    {
        printf("%d ", A[i]);
    }

    return 0;
}